<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, reactive, onMounted, watch } from 'vue'
import { ElRow, ElCol, ElCard, ElDatePicker, ElCascader, ElMessage } from 'element-plus'
import { Echart } from '@/components/Echart'
import { EChartsOption } from 'echarts'
import {
  getAbnormalOrderStats,
  getOrderStats,
  getAbnormalTypeStats
} from '@/api/electricityAbnormal'
import { abnorCategOptions } from '@/dicts'
import dayjs from 'dayjs'

const { t } = useI18n()

// 加载状态
const loading = ref(false)

// 日期选择
const dateRange = ref<[Date, Date] | undefined>(undefined)

const selectedType = ref([])

// 统计数据
const statisticsData = reactive({
  todayNew: 0,
  processRate: '0%',
  pendingCount: 0
})

// 异常工单统计图表
const workOrderChartOptions = reactive<any>({
  title: {
    text: '异常工单统计',
    left: 'left'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: 20,
    right: 20,
    bottom: 10,
    top: 50,
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      interval: 0,
      // rotate: 30
      formatter: function (value: string) {
        // 使用正则表达式每4个字符插入换行符
        // return value.replace(/(.{4})(?=.)/g, '$1\n')
        return value.replace(/([\w\u4e00-\u9fa5]{4})/g, '$1\n').replace(/\n$/, '') // 去除最后一个多余的换行
      },
      // 调整样式确保换行生效
      rich: {
        a: {
          align: 'center'
        }
      },
      lineHeight: 18 // 行高建议调整为字体大小的1.5倍
    }
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '异常工单数',
      type: 'bar',
      barWidth: '20px',
      data: [],
      itemStyle: {
        color: '#5B8FF9'
      }
    }
  ]
})

// 异常工单排名
const rankingData = ref<Array<{ rank: number; unit: string; count: number }>>([])

// 工单统计趋势图
const trendChartOptions = reactive<any>({
  title: {
    text: '工单统计',
    left: 'left'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['已处理', '总数'],
    top: 30
  },
  grid: {
    left: 50,
    right: 50,
    bottom: 20,
    top: 70
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '已处理',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#67C23A'
      }
    },
    {
      name: '总数',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#409EFF'
      }
    }
  ]
})
const seriesData = ref<any[]>([])
// 异常类型分析图表
const abnormalTypeChartOptions = reactive<any>({
  title: {
    text: '异常类型',
    left: 'left',
    top: 0
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    type: 'scroll',
    orient: 'vertical',
    right: 10,
    top: 'center',
    icon: 'circle',
    data: seriesData.value,
    formatter: function (name: string) {
      let total = 0
      let target
      for (let i = 0; i < seriesData.value.length; i++) {
        total += Number(seriesData.value[i].value)
        if (seriesData.value[i].name === name) {
          target = Number(seriesData.value[i].value)
        }
      }
      const arr = [
        '{a|' + name + '}',
        '{b|' + ((target / total) * 100).toFixed(2) + '%}',
        '{c|' + target + '}'
      ]
      return arr.join('  ')
    },
    textStyle: {
      // 添加
      padding: [8, 0, 0, 0],
      rich: {
        a: {
          fontSize: 15,
          width: 110
        },
        b: {
          fontSize: 15,
          width: 70,
          color: '#c1c1c1'
        },
        c: {
          fontSize: 15
        }
      }
    }
  },
  series: [
    {
      name: '异常类型',
      type: 'pie',
      radius: ['40%', '60%'],
      center: ['20%', '50%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
})

// 获取工单统计数据
const fetchAbnormalOrderStats = async () => {
  try {
    const params = getFilterParams()
    const res = await getAbnormalOrderStats(params)

    if (res?.code === 200 && res.data) {
      const { data } = res

      // 更新图表数据
      const units = data.map((item) => item.mgtOrgName || '未知单位')
      const counts = data.map((item) => item.sl || 0)

      ;(workOrderChartOptions.xAxis as any).data = units
      ;(workOrderChartOptions.series as any)[0].data = counts

      // 更新排名数据
      const sortedData = [...data].sort((a, b) => (b.sl || 0) - (a.sl || 0))
      rankingData.value = sortedData.slice(0, 10).map((item, index) => ({
        rank: index + 1,
        unit: item.mgtOrgName || '未知单位',
        count: item.sl || 0
      }))
    }
  } catch (error) {
    console.error('获取异常工单统计失败', error)
    ElMessage.error('获取异常工单统计失败')
  }
}

// 获取工单趋势统计
const fetchOrderStats = async () => {
  try {
    const params = getFilterParams()
    const res = await getOrderStats(params)

    if (res?.code === 200 && res.data) {
      const { data } = res

      // 更新工单趋势图 dwcsl待完成数量 ycsl异常数量
      const dates = data.map((item) => item.createTime)
      const newOrders = data.map((item) => item.zs)
      const completedOrders = data.map((item) => item.ycsl - item.dwcsl)

      ;(trendChartOptions.xAxis as any).data = dates
      ;(trendChartOptions.series as any)[0].data = completedOrders
      ;(trendChartOptions.series as any)[1].data = newOrders

      // 更新统计数据
      if (data) {
        // 计算today累加值 - 累加数据中所有项的zs值
        statisticsData.todayNew = data.reduce((sum, item) => {
          // 确保zs存在且为数字，如果不是则加0
          const zsValue = item.zs && !isNaN(Number(item.zs)) ? Number(item.zs) : 0
          return sum + zsValue
        }, 0)
        statisticsData.pendingCount = data.reduce((sum, item) => {
          // 确保zs存在且为数字，如果不是则加0
          const dwcslValue = item.dwcsl && !isNaN(Number(item.dwcsl)) ? Number(item.dwcsl) : 0
          return sum + dwcslValue
        }, 0)
        const processRate = (
          ((statisticsData.pendingCount || 0) / (statisticsData.todayNew || 0)) *
          100
        ).toFixed(2)
        statisticsData.processRate = isNaN(Number(processRate)) ? '0%' : processRate + '%'
      }
    }
  } catch (error) {
    console.error('获取工单统计失败', error)
    ElMessage.error('获取工单统计失败')
  }
}

// 获取异常类型统计
const fetchAbnormalTypeStats = async () => {
  try {
    const params = getFilterParams()

    if (
      selectedType.value &&
      selectedType.value.length > 0 &&
      selectedType.value[0][0] !== '全部'
    ) {
      // 异常类别
      const abnorTypeList = ref([])
      // 异常类型
      const abnorCategList = ref([])
      abnorTypeList.value = selectedType.value.map((item) => item[0])
      abnorCategList.value = selectedType.value.map((item) => item[1])
      params.abnorTypeList = abnorTypeList.value
      params.abnorCategList = abnorCategList.value
      console.log('abnorTypeList', abnorTypeList.value)
      console.log('abnorCategList', abnorCategList.value)
    }

    const res = await getAbnormalTypeStats(params)

    if (res?.code === 200 && res.data) {
      const { data } = res

      // 更新饼图数据
      const legendData = data.map((item) => item.abnorCateg || '未知类型')
      seriesData.value = data.map((item, index) => {
        const colors = ['#5B8FF9', '#5AD8A6', '#FFD43B', '#E15554', '#9D63FF', '#59D4E8']
        return {
          value: item.sl || 0,
          name: item.abnorCateg || '未知类型',
          itemStyle: { color: colors[index % colors.length] }
        }
      })
      console.log('seriesData', seriesData.value)
      console.log('legendData', legendData)
      ;(abnormalTypeChartOptions.legend as any).data = legendData
      ;(abnormalTypeChartOptions.series as any)[0].data = seriesData.value
    }
  } catch (error) {
    console.error('获取异常类型统计失败', error)
    ElMessage.error('获取异常类型统计失败')
  }
}

// 获取筛选参数
const getFilterParams = () => {
  const params: Record<string, any> = {}

  if (dateRange.value && dateRange.value.length === 2) {
    params.startExpYm = dayjs(dateRange.value[0]).format('YYYYMM')
    params.endExpYm = dayjs(dateRange.value[1]).format('YYYYMM')
  }
  // params.pageNum = '1'
  // params.pageSize = '10'

  return params
}

// 加载所有数据
const loadAllData = async () => {
  loading.value = true
  try {
    await Promise.all([fetchAbnormalOrderStats(), fetchOrderStats(), fetchAbnormalTypeStats()])
  } catch (error) {
    console.error('加载数据失败', error)
  } finally {
    loading.value = false
  }
}
const props2 = {
  multiple: true,
  checkStrictly: false // 父子关联开关
}

// 获取上个月的起止日期（YYYYMM格式）
const getPreviousMonthRange = (): [Date, Date] => {
  const currentDate = dayjs()
  const previousMonth = currentDate.subtract(1, 'month')
  const startDate = previousMonth.startOf('month').toDate()
  const endDate = previousMonth.endOf('month').toDate()
  return [startDate, endDate]
}

// 监听过滤条件变化
watch([dateRange, selectedType], () => {
  loadAllData()
})

// 组件挂载时加载数据
onMounted(() => {
  dateRange.value = getPreviousMonthRange()
  loadAllData()
})
</script>

<template>
  <ContentWrap :loading="loading">
    <!-- 头部日期选择栏 -->
    <div class="filter-wrap">
      <span style="display: inline-block; width: calc(100% - 440px)"></span>
      <span class="filter-container">
        <ElDatePicker
          v-model="dateRange"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始年月"
          end-placeholder="结束年月"
          size="default"
          class="date-picker"
          popper-placement="bottom-start"
        />
      </span>
    </div>

    <!-- 工单统计与排名 -->
    <ElRow :gutter="10" class="mb-20px">
      <ElCol :span="15">
        <ElCard shadow="hover" class="chart-card">
          <Echart :options="workOrderChartOptions" :height="306" />
        </ElCard>
      </ElCol>
      <ElCol :span="9">
        <ElCard shadow="hover" class="chart-card ranking-card">
          <div class="card-title">异常工单排名</div>
          <div class="ranking-list">
            <div v-for="item in rankingData" :key="item.rank" class="ranking-item">
              <div class="rank-number" :class="{ 'top-rank': item.rank <= 3 }">{{ item.rank }}</div>
              <div class="rank-info">
                <div class="rank-name">{{ item.unit }}</div>
                <div class="rank-count">{{ item.count }}</div>
              </div>
            </div>
          </div>
        </ElCard>
      </ElCol>
    </ElRow>

    <!-- 工单统计与异常类型分析 -->
    <ElRow :gutter="10">
      <ElCol :span="15">
        <ElCard shadow="hover" class="chart-card">
          <div class="statistics-header">
            <div class="statistics-item">
              <div class="statistics-label">导入数据</div>
              <div class="statistics-value"
                >{{ statisticsData.todayNew }}<span class="statistics-unit">条</span></div
              >
            </div>
            <div class="statistics-item">
              <div class="statistics-label">异常率</div>
              <div class="statistics-value">{{ statisticsData.processRate }}</div>
            </div>
            <div class="statistics-item">
              <div class="statistics-label">待完成</div>
              <div class="statistics-value"
                >{{ statisticsData.pendingCount }}<span class="statistics-unit">个</span></div
              >
            </div>
          </div>
          <Echart :options="trendChartOptions" :height="280" />
        </ElCard>
      </ElCol>
      <ElCol :span="9">
        <ElCard shadow="hover" class="chart-card">
          <div class="type-select">
            <ElCascader
              :options="abnorCategOptions"
              v-model="selectedType"
              :props="props2"
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="1"
              clearable
              placeholder="请选择异常类型"
              style="width: 315px"
            />
          </div>
          <Echart class="chart-margin" :options="abnormalTypeChartOptions" :height="310" />
        </ElCard>
      </ElCol>
    </ElRow>
  </ContentWrap>
</template>

<style lang="scss" scoped>
.filter-wrap {
  margin-bottom: 16px;
}

.filter-container {
  width: 300px;

  .date-picker {
    width: 280px;
    margin-left: 10px;
  }
}

.chart-card {
  position: relative;
  height: 100%;
}

.ranking-card {
  .card-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
    text-align: left;
  }

  .ranking-list {
    padding: 0 10px;
    max-height: 268.8px;
    overflow-y: auto;
    scrollbar-width: thin; /* 可选：auto | thin | none */
    scrollbar-color: #888 #f1f1f1; /* 滑块颜色 轨道颜色 */
    // scrollbar-width: none; /* 隐藏滚动条（Firefox） */
    // -ms-overflow-style: none; /* 隐藏滚动条（IE/Edge） */
  }

  .ranking-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .rank-number {
      width: 24px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      border-radius: 50%;
      background-color: #f5f5f5;
      color: #666;
      font-size: 14px;
      font-weight: 600;
      margin-right: 10px;

      &.top-rank {
        background-color: #409eff;
        color: white;
      }
    }

    .rank-info {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .rank-name {
        font-size: 14px;
      }

      .rank-count {
        font-size: 14px;
        font-weight: 600;
        color: #333;
      }
    }
  }
}

.statistics-header {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;

  .statistics-item {
    text-align: center;

    .statistics-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 5px;
    }

    .statistics-value {
      font-size: 24px;
      font-weight: 600;
      color: #333;

      .statistics-unit {
        font-size: 14px;
        font-weight: normal;
        margin-left: 2px;
      }
    }
  }
}

.type-select {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1;
}
.chart-margin {
  margin-top: 40px;
}
</style>
